package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String publish(Movement movement) {
        try {
            //设置Pid
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);

            //查询好友
            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
            Query query = Query.query(criteria);
            List<Friend> friends = mongoTemplate.find(query, Friend.class);
            for (Friend friend : friends) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setFriendId(friend.getFriendId());
                movementTimeLine.setUserId(friend.getUserId());
                movementTimeLine.setCreated(System.currentTimeMillis());
                movementTimeLine.setMovementId(movement.getId());
                mongoTemplate.save(movementTimeLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
           return movement.getId().toHexString();
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = new Query(criteria);
        //查询总共有多少条动态
        long count = mongoTemplate.count(query, Movement.class);
        String count1 = count+"";
        Integer integer = Integer.valueOf(count1);
        //分页查询动态
        query.skip((page-1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pr = new PageResult(page,pagesize,integer,movements);
        return pr;
    }


    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {
        //获取movement_timeline表里面的好友动态ID 以及排序
        Criteria criteria = Criteria.where("friendId").is(friendId);
        Query query = new Query(criteria)
                .skip((page - 1)* pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //抽取动态ID
        List<Object> movementId = CollUtil.getFieldValues(movementTimeLines, "movementId", Object.class);
        Query query1 = Query.query(criteria.where("id").in(movementId));
        List<Movement> movements = mongoTemplate.find(query1, Movement.class);
        return movements;
    }

    /**
     * 随机往redis里面存入十条动态数据
     * @param counts
     * @return
     */
    @Override
    public List<Movement> randomMovements(Integer counts) {
       //Query query = new Query(Criteria.where("pid").)
        //创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(counts));
        //调用mongotemplate方法统计
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(aggregation, Movement.class);
        return aggregate.getMappedResults();
    }

    /**
     * 根据PID查询动态
     * @param pid
     * @return
     */
    @Override
    public List<Movement> findMovementsByPids(List<Long> pid) {
        Query query = new Query(Criteria.where("pid").in(pid));
        return mongoTemplate.find(query, Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        return movement;
    }

    @Override
    public boolean love(String movementId, Long userId, CommentType love) {
        //查询是否已经点了喜欢
        Query query = new Query(Criteria.where("userId").is(userId)
        .and("publishId").is(new ObjectId(movementId))
        .and("commentType").is(love.getType()));
        return mongoTemplate.exists(query, Comment.class);
    }

    @Override
    public Integer updateLove(Comment comment) {
        //查询movement表 更新喜欢动态 取出userid  给comment赋值
        Query query = new Query(Criteria.where("id").is(comment.getPublishId().toHexString()));
        Update update = new Update();
        if (comment.getCommentType()==CommentType.LOVE.getType()) {
            update.inc("loveCount",1);
        }else if (comment.getCommentType() == CommentType.LIKE.getType()){
            update.inc("likeCount",1);
        }else {
            update.inc("commentCount",1);
        }
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);
        Movement andModify = mongoTemplate.findAndModify(query, update, modify, Movement.class);
        //取出userid 给comment赋值 保存到数据库
        comment.setPublishUserId(andModify.getUserId());
        mongoTemplate.save(comment);

        return andModify.statisCount(comment.getCommentType());
    }

    @Override
    public Integer deleteLove(Comment comment) {
/*        //先更新movement表，然后取出movement对象中的userid封装到comment上
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = new Query(criteria);
        mongoTemplate.remove(query,Comment.class);
        Update update = new Update();
        if (comment.getCommentType()==CommentType.LOVE.getType()) {
            update.inc("loveCount",-1);
        }else if (comment.getCommentType() == CommentType.LIKE.getType()){
            update.inc("likeCount",-1);
        }else {
            update.inc("commentCount",-1);
        }
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);
        Movement andModify = mongoTemplate.findAndModify(query, update, modify, Movement.class);
        return andModify.statisCount(comment.getCommentType());*/
        //查询到点赞数据
        Query query = Query.query(Criteria.where("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType())
                .and("userId").is(comment.getUserId()));
        //删除comment表里面的点赞记录
        mongoTemplate.remove(query,Comment.class);
        //movement表里面的点赞记录 -1
        Query query1 = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()){
            update.inc("likeCount",-1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount",-1);
        }else {
            update.inc("loveCount",-1);
        }

        //设置更新参数
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);

        Movement andModify = mongoTemplate.findAndModify(query1, update, modify, Movement.class);
        return andModify.statisCount(comment.getCommentType());
    }

    @Override
    public PageResult findByUserIds(Long uid, Integer state, Integer page, Integer pagesize) {
        Query query = new Query();
        if(uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        //查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //设置分页参数
        query.with(Sort.by(Sort.Order.desc("created"))).limit(pagesize).skip((page -1) * pagesize);

        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public void update(String movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }
}
